import { defineStore } from 'pinia'
import { getUserInfoAPI } from '@/api/user'
import { ref } from 'vue'
import { loginLogAPI } from '@/api/loginLog'
import { loginAPI } from '@/api/login'

import router from '@/router'

export const useUserStore = defineStore(
  'user',
  () => {
    const UserInfo = ref<UserInfoData>({})
    /** 登录 */
    const login = async (account: number, password: string) => {
      const res = await loginAPI(account, password)
      localStorage.setItem('TOKEN', res.token!)
      return res.data
    }

    /** 获取用户信息 */
    const getUserInfo = async (id: number) => {
      const res = await getUserInfoAPI(id)
      UserInfo.value = res
      /** 记录登录 */
      loginLogAPI(UserInfo.value?.account!, UserInfo.value?.name!, UserInfo.value?.email!)
    }

    /** 退出登录 */
    const logout = () => {
      localStorage.clear()
      router.push('/login')
      UserInfo.value = {}
    }
    return { UserInfo, login, logout, getUserInfo }
  },
  {
    persist: {
      // 持久化
      key: 'UserInfo'
    }
  }
)
